<script setup>
import { ref,watch } from 'vue';
import { ElMessage, ElTag } from 'element-plus';
import { useRouter } from 'vue-router';
import { orderQueryPage,selectByOrderId } from '@/api/Order';



const router = useRouter(); // 获得路由对象
const searchQuery = ref('');
// 请求参数数据模型
const queryPageParam = ref({
  pageNum: 1,
  pageSize: 5, 
  onum: "",//模糊匹配，注意：若后端是数值类型，需转字符串）
  ostate:"",
 
});
const currentOrder =ref({})
const orderShoes =ref({})

const orderList = ref([]);
const detailVisible = ref(false);

// 下拉列表选项（从步骤1引入或直接定义）
const statusOptions = [
  { label: "全部订单", value: '' },
  { label: "待发货订单", value: 6 },
  { label: "运输中订单", value: 1 },
  { label: "交易成功订单", value: 2 },
  { label: "申请退货订单", value: 3 },
  { label: "已退货订单", value: 4 },
  { label: "已取消订单", value: 5 }
];

const formatTime = (isoTime) => {
  if (!isoTime) return '暂无数据';
  // 转换ISO时间为本地时间，并格式化为"YYYY-MM-DD HH:mm:ss"
  return dayjs(isoTime).format('YYYY-MM-DD HH:mm:ss');
};
const getStatusText = (stateValue) => {
  // 遍历 statusOptions，匹配 value 对应的 label
  const matchedOption = statusOptions.find(option => {
    // 注意：空字符串（全部订单）只在筛选时用，表格中订单状态不会是空，这里兼容异常情况
    return option.value === stateValue;
  });
  // 若匹配到则返回 label，未匹配到（如后端返回异常值）返回“未知状态”
  return matchedOption ? matchedOption.label : "未知状态";
};
const getStatusTagType = (stateValue) => {
  // 基于 statusOptions 的 value 定义标签颜色，与业务状态语义匹配
  switch (stateValue) {
    case 2: // 交易成功订单 → 绿色（成功）
      return "success";
    case 1: // 运输中订单 → 橙色（待处理）
    case 3: // 申请退货订单 → 橙色（待处理）
      return "warning";
    case 5: // 已取消订单 → 红色（异常）
      return "danger";
    case 6: // 待发货订单 → 蓝色（常规）
    case 4: // 已退货订单 → 蓝色（常规）
      return "info";
    default: // 空字符串（筛选全部）或异常值 → 灰色（默认）
      return "default";
  }
};

// 请求订单函数
function queryOrder() {
  orderQueryPage(queryPageParam.value.ostate,queryPageParam.value.onum,queryPageParam.value.pageNum, 
  queryPageParam.value.pageSize)
    .then(data => {
      // 将数据赋值给数据模型
      orderList.value = data.list || [];
      // 假设接口返回的分页信息包含总记录数
      queryPageParam.value.recordCount = data.pager?.recordCount || 0;
      console.log(orderList, queryPageParam)
    })
    .catch(error => {
      ElMessage.error('获取订单列表失败：' + (error.message || '未知错误'));
    });
}




// 1. 防抖定时器（用于清除上一次的延迟查询）
let searchTimer = null;
// 4. 防抖搜索核心函数  增加 immediate 参数（默认 false）
const debounceSearch = async (immediate = false) => {
  // 第一步：清除上一次的定时器（防止重复触发）
  if (searchTimer) {
    clearTimeout(searchTimer);
  }

// 定义核心查询逻辑（抽成函数，避免重复代码）
  const doSearch = async () => {
    try {
      // 重置页码（搜索时从第1页开始）
      queryPageParam.value.pageNum = 1;
      // 赋值搜索参数
      const searchVal = searchQuery.value.trim();
      queryPageParam.value.onum = searchVal;
      
      // 发起请求（await 等待结果）
        queryOrder();

    } catch (err) {
      ElMessage.error('查询失败，请重试');
      console.error('搜索错误：', err);
    }
  };

  // 关键逻辑：根据 immediate 决定是否立即执行
  if (immediate) {
    // 手动触发：立即执行查询（无延迟）
    await doSearch();
  } else {
    // 自动输入：延迟 500ms 执行（防抖）
    searchTimer = setTimeout(doSearch, 500);
  }
};

    // 5. 监听输入框变化，自动触发防抖搜索
    watch(searchQuery, (newVal) => {
      // 输入变化时，立即执行防抖逻辑
      debounceSearch();
    }, {
      immediate: true // 初始加载时，若 searchQuery 有默认值，也触发一次查询
    });

// 搜索订单
const handleSearch = () => {
  debounceSearch(true); // 手动触发 → 立即执行
};

// 处理编辑订单
const handleEdit = (row) => {
  router.push(`/order/edit/${row.oid}`); // 假设编辑订单路由为/order/edit/:id
};

// 删除订单方法
const deleteGoods = (index, orderId) => {
  // 这里应该有删除订单的逻辑
  ElMessage.success(`已删除订单 ID: ${orderId}`);
  // 删除后重新加载数据
  queryOrder();
};

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};

// 行点击事件
const handleRowClick = (row) => {
  console.log('点击了行:', row);
  // 可以在这里实现点击行查看详情等功能
};

const handleDelete = async (id) => {
  try {
    console.log("执行了 删除")
    await deleteById(id);
    handleSearch()
  } catch (error) {
    console.error('删除失败:', error);
  }
};



const showOrderDetail=(order) =>{
  // 深拷贝用户对象，避免修改弹窗内容影响表格数据
  
    console.log("order---->",order.oid)
  currentOrder.value = JSON.parse(JSON.stringify(order))

  selectByOrderId(order.oid).then(res => {
      orderShoes.value=res
      console.log("order.oid---->",order.oid)
        console.log("typeof order.oid---->",typeof order.oid)
        console.log("orderShoes.value",orderShoes.value.osid)
    })
    .catch(error => {
      ElMessage.error('获取orderShoes信息失败：' + (error.message || '未知错误'));
    });



  // 显示弹窗
  detailVisible.value = true

 
}
//辅助函数：处理空值显示（null/undefined 时显示“--”）
const formatNullValue = (value) => {
  return value === null || value === undefined ? '--' : value;
};
const formatIsoDate = (isoDate) => {
  if (!isoDate) return '--';
  const date = new Date(isoDate);
  // 处理时区（UTC+8），避免时间差
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  // 处理字符串类型的日期
  if (typeof date === 'string') {
    // 尝试转换为Date对象
    const dateObj = new Date(date);
    if (!isNaN(dateObj.getTime())) {
      date = dateObj;
    } else {
      return date;
    }
  }
  
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

const handleDetail = (id) => router.push({ path: '/order/OrderDetailView', query: { id } });
</script>

<template>
  <div class="order-management-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>订单管理中心</h1>
      <p>查看和管理所有订单信息，支持筛选、编辑和删除操作</p>
    </div>

    <!-- 订单表格卡片 -->
    <el-card class="order-table-card">
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <el-input 
          placeholder="搜索订单号或用户ID" 
          v-model="searchQuery" 
          clearable
          size="small"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" size="small" @click="handleSearch" class="search-btn"></el-button>
          </template>
        </el-input>
        <el-select 
          v-model="queryPageParam.ostate" 
          placeholder="请选择订单状态"
          @change="handleSearch"
          size="small"
          class="status-select"
        >
          <el-option 
            v-for="item in statusOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value"
          />
        </el-select>
     
      </div>

      <!-- 订单表格 -->
      <el-table 
        :data="orderList" 
        style="width: 100%"
        border
        :header-cell-style="{ background: '#f0f5ff', color: '#409eff', fontWeight: '500' }"
        :row-class-name="tableRowClassName"
        @row-click="handleRowClick"
        highlight-current-row
        :empty-text="orderList.length === 0 ? '暂无订单数据' : '加载中...'"
        class="order-table"
      >
        <el-table-column fixed prop="oid" label="订单ID" width="100" align="center" />
        <el-table-column fixed prop="onum" label="订单编号" width="180" align="center" />
        <el-table-column prop="ostate" label="订单状态" width="120" align="center">
          <template #default="scope">
        <!-- 直接调用两个映射函数，获取标签类型和中文文本 -->
        <el-tag :type="getStatusTagType(scope.row.ostate)">
          {{ getStatusText(scope.row.ostate) }}
        </el-tag>
      </template>
        </el-table-column>
        <el-table-column prop="ordertime" label="下单时间" width="180" align="center" >
          <template #default="scope">
            {{ formatDateTime(scope.row.ordertime) }}
          </template>
        </el-table-column>
         
        <el-table-column prop="ototal" label="总价" width="120" align="center">
          <template #default="scope">
            ¥{{ scope.row.ototal.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="oexpinfo" label="快递跟踪" width="180" align="center" />
        <el-table-column prop="ointegral" label="总积分" width="120" align="center" />
        <el-table-column prop="onote" label="备注" width="180" align="center" />
        <el-table-column prop="userId" label="用户ID" width="120" align="center" />
        <el-table-column prop="user.uname" label="用户姓名" width="120" align="center" />
        <el-table-column prop="receiveId" label="收货信息ID" width="140" align="center" />
        
        <el-table-column fixed="right" label="操作" min-width="160" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showOrderDetail(scope.row)" >
              <Edit class="mr-1" /> 查看
            </el-button>
            
            <!-- 删除按钮弹出气泡确认框 -->
            <el-popconfirm 
              title="确定要删除此订单吗?"
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="red"
              @confirm="handleDelete( scope.row.oid)"
            >
              <template #reference>
                <el-button type="danger" size="small" class="delete-btn ml-2">
                  <Delete class="mr-1" /> 删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryPageParam.pageNum"
          v-model:page-size="queryPageParam.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="queryPageParam.recordCount"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="queryOrder"
          @current-change="queryOrder"
          class="pagination"
        />
      </div>
    </el-card>
  </div>
   <!-- 订单详情对话框 -->
<el-dialog 
  title="订单详情" 
  v-model="detailVisible" 
  width="70%"  
  :close-on-click-modal="false" 
  :destroy-on-close="true"  
>
  <div class="order-detail-container">
    <!-- 1. 订单基础信息区域 -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <h3 class="section-title">基础信息</h3>
        <el-descriptions 
          border 
          column="3" 
          :label-width="120"   
        >
          <el-descriptions-item label="订单ID">{{ formatNullValue(currentOrder.oid) }}</el-descriptions-item>
          <el-descriptions-item label="订单编号">{{ formatNullValue(currentOrder.onum) }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">{{ getStatusText(currentOrder.ostate) }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatIsoDate(currentOrder.ordertime) }}</el-descriptions-item>
          <el-descriptions-item label="订单总价">¥{{ formatNullValue(currentOrder.ototal?.toFixed(2)) }}</el-descriptions-item>
          <el-descriptions-item label="快递跟踪">{{ formatNullValue(currentOrder.oexpinfo) }}</el-descriptions-item>
          <el-descriptions-item label="使用积分">{{ formatNullValue(currentOrder.ointegral) }}</el-descriptions-item>
          <el-descriptions-item label="订单备注">{{ formatNullValue(currentOrder.onote) }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ formatNullValue(currentOrder.userId) }}</el-descriptions-item>
          <el-descriptions-item label="收货信息ID">{{ formatNullValue(currentOrder.receiveId) }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    <!-- 新增：订单项信息区域 -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <h3 class="section-title">订单项信息</h3>
        <el-descriptions 
          border 
          column="3" 
          :label-width="120"
        >
          <!-- 订单项自身信息 -->
          <el-descriptions-item label="订单项ID">{{ formatNullValue(orderShoes.osid) }}</el-descriptions-item>
          <el-descriptions-item label="商品尺码">{{ formatNullValue(orderShoes.ossize) }}</el-descriptions-item>
          <el-descriptions-item label="订单项状态">{{ getStatusText(orderShoes.osstate) }}</el-descriptions-item>
          <el-descriptions-item label="购买数量">{{ formatNullValue(orderShoes.osnum) }}</el-descriptions-item>
          <el-descriptions-item label="订单项备注">{{ formatNullValue(orderShoes.oremarks) }}</el-descriptions-item>
          <el-descriptions-item label="关联订单ID">{{ formatNullValue(orderShoes.orderId) }}</el-descriptions-item>
          <el-descriptions-item label="关联商品ID">{{ formatNullValue(orderShoes.shoeId) }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    <!-- 新增：商品信息区域（从orderShoes.shoes获取） -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <h3 class="section-title">商品信息</h3>
        <el-descriptions 
          border 
          column="3" 
          :label-width="120"
        >
          <el-descriptions-item label="商品ID">{{ formatNullValue(orderShoes.shoes?.sid) }}</el-descriptions-item>
          <el-descriptions-item label="商品编号">{{ formatNullValue(orderShoes.shoes?.snum) }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ formatNullValue(orderShoes.shoes?.sname) }}</el-descriptions-item>
          <el-descriptions-item label="原价">¥{{ formatNullValue(orderShoes.shoes?.sprices?.toFixed(2)) }}</el-descriptions-item>
          <el-descriptions-item label="折扣价">¥{{ formatNullValue(orderShoes.shoes?.sdiscount?.toFixed(2)) }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ formatIsoDate(orderShoes.shoes?.spubtime) }}</el-descriptions-item>
          <el-descriptions-item label="生产厂商">{{ formatNullValue(orderShoes.shoes?.sproducer) }}</el-descriptions-item>
          <el-descriptions-item label="适用性别">{{ formatNullValue(orderShoes.shoes?.sgender) }}</el-descriptions-item>
          <el-descriptions-item label="销售数量">{{ formatNullValue(orderShoes.shoes?.stimessold) }}</el-descriptions-item>
          <el-descriptions-item label="所需积分">{{ formatNullValue(orderShoes.shoes?.sintegral) }}</el-descriptions-item>
          <el-descriptions-item label="类型ID">{{ formatNullValue(orderShoes.shoes?.typeId) }}</el-descriptions-item>
          <el-descriptions-item label="品牌ID">{{ formatNullValue(orderShoes.shoes?.brandId) }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    <!-- 3. 用户信息区域 -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <h3 class="section-title">用户信息</h3>
        <el-descriptions 
          border 
          column="3" 
          :label-width="120"
        >
          <el-descriptions-item label="用户ID">{{ formatNullValue(currentOrder.user?.uid) }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ formatNullValue(currentOrder.user?.uname) }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ formatNullValue(currentOrder.user?.utel) }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ formatNullValue(currentOrder.user?.ugender) }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ formatNullValue(currentOrder.user?.uemail) }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ formatIsoDate(currentOrder.user?.uregtime) }}</el-descriptions-item>
          <el-descriptions-item label="用户积分">{{ formatNullValue(currentOrder.user?.uintegral) }}</el-descriptions-item>
          <el-descriptions-item label="用户备注">{{ formatNullValue(currentOrder.user?.uremarks) }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>

    <!-- 4. 收货信息区域 -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <h3 class="section-title">收货信息</h3>
        <el-descriptions 
          border 
          column="3" 
          :label-width="120"
        >
          <el-descriptions-item label="收货ID">{{ formatNullValue(currentOrder.receives?.recid) }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{ formatNullValue(currentOrder.receives?.recprovince) }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{ formatNullValue(currentOrder.receives?.reccity) }}</el-descriptions-item>
          <el-descriptions-item label="区域">{{ formatNullValue(currentOrder.receives?.recdistrict) }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ formatNullValue(currentOrder.receives?.recstreet) }}</el-descriptions-item>
          <el-descriptions-item label="固定电话">{{ formatNullValue(currentOrder.receives?.rectel) }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ formatNullValue(currentOrder.receives?.recmobile) }}</el-descriptions-item>
          <el-descriptions-item label="邮政编码">{{ formatNullValue(currentOrder.receives?.recpostcode) }}</el-descriptions-item>
          <el-descriptions-item label="收货人">{{ formatNullValue(currentOrder.receives?.recreceiver) }}</el-descriptions-item>
          <el-descriptions-item label="是否默认地址">{{ formatNullValue(currentOrder.receives?.recisdefault ? '是' : '否') }}</el-descriptions-item>
        </el-descriptions>
      </el-col>
    </el-row>
  </div>
</el-dialog>

    
  
</template>

<style scoped>
/* 全局容器与背景 */
.order-management-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  margin-bottom: 32px;
  color: #303133;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.page-header h1 {
  font-size: 28px;
  margin-bottom: 12px;
  font-weight: 600;
  color: #2c3e50;
}

.page-header p {
  color: #606266;
  font-size: 14px;
  opacity: 0.9;
}

/* 卡片容器 */
.order-table-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #fff;
}

.order-table-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #eaeaea;
  gap: 16px;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
  flex-shrink: 0;
}

/* 搜索按钮 */
.search-btn {
  background-color: #409eff;
  color: #fff;
  &:hover {
    background-color: #66b1ff;
  }
}

/* 状态选择器 */
.status-select {
  width: 180px;
  flex-shrink: 0;
}

/* 新增按钮 */
.add-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  &:hover {
    background-color: #85ce61;
    border-color: #85ce61;
  }
}

/* 订单表格 */
.order-table {
  margin-top: 16px;
}

/* 表格行样式 */
::v-deep .table-row-even {
  background-color: #f9fafc;
}

::v-deep .table-row-odd {
  background-color: #ffffff;
}

::v-deep .el-table tr:hover > td {
  background-color: #e6f7ff !important;
  transition: background-color 0.3s ease;
}

::v-deep .el-table__row--current > td {
  background-color: #d9ecff !important;
}

/* 状态标签颜色优化 */
::v-deep .el-tag--success {
  background-color: #f0f9eb;
  color: #67c23a;
  border-color: #e1f3d8;
}
::v-deep .el-tag--warning {
  background-color: #fdf6ec;
  color: #e6a23c;
  border-color: #faecd8;
}
::v-deep .el-tag--danger {
  background-color: #fef0f0;
  color: #f56c6c;
  border-color: #fde2e2;
}
::v-deep .el-tag--info {
  background-color: #f0f2f5;
  color: #909399;
  border-color: #e4e7ed;
}

/* 操作按钮交互优化 */
::v-deep .edit-btn {
  background-color: #409eff;
  border-color: #409eff;
  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
    transform: translateY(-1px);
  }
}

::v-deep .delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  &:hover {
    background-color: #f78989;
    border-color: #f78989;
    transform: translateY(-1px);
  }
}

/* 分页组件样式优化 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 24px;
  border-top: 1px solid #eaeaea;
}

.pagination {
  &::v-deep .el-pagination__total {
    margin-right: 16px;
    color: #606266;
  }
  &::v-deep .el-pagination__sizes {
    margin-right: 16px;
  }
  &::v-deep .el-pagination__button {
    border-radius: 4px;
    margin: 0 2px;
  }
  &::v-deep .el-pagination__button:hover {
    color: #409eff;
  }
  &::v-deep .el-pagination__current {
    background-color: #409eff;
    border-color: #409eff;
  }
}

/* 响应式适配 */
@media (max-width: 768px) {
  .order-management-container {
    padding: 16px;
  }
  
  .table-toolbar {
    gap: 12px;
  }
  
  .search-input, .status-select {
    width: 100%;
  }
  
  .pagination-container {
    justify-content: center;
  }
}
/* 订单详情对话框样式 */
.order-detail-container {
  padding: 10px 0;
}

/* 详情区域标题（基础信息/用户信息等） */
.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

/* 详情区域间距 */
.detail-section {
  margin-bottom: 20px;
}

/* 适配小屏幕：调整详情字段列数 */
@media (max-width: 1200px) {
  ::v-deep .el-descriptions {
    column-count: 2 !important; /* 中等屏幕一行2个字段 */
  }
}

@media (max-width: 768px) {
  ::v-deep .el-descriptions {
    column-count: 1 !important; /* 小屏幕一行1个字段 */
  }
  .el-dialog {
    width: 95% !important; /* 小屏幕对话框占满宽度 */
  }
}
</style>
